<script lang="ts" setup>
import type { InfraCodegenApi } from '#/api/infra/codegen';
import type { SystemDictTypeWithDataApi } from '#/api/system/dict/type';

import { reactive, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import {
  Button,
  Card,
  Checkbox,
  Input,
  message,
  Select,
  Table,
  Tag,
} from 'ant-design-vue';

import { getCodegenTable } from '#/api/infra/codegen';
import { createDictTypeWithDataBatch } from '#/api/system/dict/type';
import { colorOptions, colorOptionsValue } from '#/views/system/dict/data';

interface SelectedColumn extends SystemDictTypeWithDataApi.DictTypeWithData {
  checked: boolean;
  tableId: number;
  tableName: string;
}

/** 组件状态 */
const loading = ref(false);
const selectedTables = ref<InfraCodegenApi.CodegenTable[]>([]);
const tableColumns = reactive<Array<SelectedColumn>>([]);

/** 获取表格列信息 */
async function fetchTableColumns() {
  if (
    !selectedTables.value ||
    !Array.isArray(selectedTables.value) ||
    selectedTables.value.length === 0
  ) {
    return;
  }

  loading.value = true;
  try {
    const promises = selectedTables.value.map(async (table) => {
      const detail = await getCodegenTable(table.id);
      return getIntegerAndLongColumns(detail);
    });

    tableColumns.push(
      // eslint-disable-next-line unicorn/no-await-expression-member
      ...((await Promise.all(promises)).flat() as SelectedColumn[]),
    );
  } catch (error) {
    console.error('获取表格列信息失败:', error);
    message.error('获取表格列信息失败');
  } finally {
    loading.value = false;
  }
}

/** 筛选需要添加字典的字段 */
function getIntegerAndLongColumns(detail: InfraCodegenApi.CodegenDetail) {
  const result: Array<SelectedColumn> = [];
  const integerLongColumns = detail.columns.filter(
    (column) => column.dataType === 'BIGINT' && !column.primaryKey,
  );

  integerLongColumns.forEach((column) => {
    result.push({
      checked: false,
      tableId: detail.table.id,
      tableName: detail.table.tableName,
      name: column.columnComment,
      type: column.columnName,
      remark: column.columnComment,
      status: 0,
      data: [
        {
          createTime: new Date(),
          dictType: column.columnName,
          value: '1',
          label: '',
          remark: column.columnComment,
          sort: 1,
          status: 0,
          colorType: colorOptionsValue[0] || 'success',
          cssClass: '',
        },
      ],
      createTime: new Date(),
    });
  });

  return result;
}

/** 全选功能 */
function handleSelectAll() {
  tableColumns.forEach((item) => (item.checked = true));
}

/** 批量添加字典 */
async function handleBatchAddDict() {
  if (tableColumns.filter((item) => item.checked).length === 0) {
    message.warning('请选择要添加字典的字段');
    return;
  }

  const hideLoading = message.loading({
    content: '正在批量添加字典中...',
    key: 'action_key_msg',
  });
  try {
    await createDictTypeWithDataBatch(
      tableColumns.filter((item) => item.checked),
    );
    message.success({
      content: `成功添加 ${tableColumns.filter((item) => item.checked).length} 个字段的字典数据`,
      key: 'action_key_msg',
    });

    // 关闭模态框
    modalApi.close();
  } catch (error) {
    console.error('批量添加字典失败:', error);
    message.error('批量添加字典失败');
  } finally {
    hideLoading();
  }
}

/** 模态框实例 */
const [Modal, modalApi] = useVbenModal({
  class: 'w-3/4',
  footer: true,
  closeOnClickModal: false,
  onOpened() {
    const data = modalApi.getData();

    // 确保数据是数组格式
    if (Array.isArray(data)) {
      selectedTables.value = data;
    } else if (data && Array.isArray(data.value)) {
      selectedTables.value = data.value;
    } else {
      selectedTables.value = [];
    }
    fetchTableColumns();
  },
  onConfirm: handleBatchAddDict,
});
</script>

<template>
  <Modal title="批量添加字典">
    <div v-loading="loading" class="space-y-4">
      <!-- 已选择的表格信息 -->
      <Card size="small" title="已选择的表格">
        <div class="flex flex-wrap gap-2">
          <Tag v-for="table in selectedTables" :key="table.id" color="blue">
            {{ table.tableName }}
          </Tag>
        </div>
      </Card>

      <!-- 字段列表 -->
      <Card size="small" title="Integer 和 Long 类型字段">
        <div class="mb-4">
          <Button type="primary" size="small" @click="handleSelectAll">
            全选
          </Button>
          <Button
            size="small"
            class="ml-2"
            @click="tableColumns.forEach((item) => (item.checked = false))"
          >
            清空
          </Button>
          <span class="ml-4 text-gray-500">
            已选择 {{ tableColumns.filter((item) => item.checked).length }} 个字段
          </span>
        </div>

        <Table
          :columns="[
            {
              title: '选择',
              dataIndex: 'checked',
              key: 'checked',
              width: 60,
            },
            {
              title: '字典名称',
              dataIndex: 'dictName',
              key: 'dictName',
              width: 300,
            },
            {
              title: '字典类型',
              dataIndex: 'dictType',
              key: 'dictType',
              width: 300,
            },
            {
              title: '数据标签',
              dataIndex: 'dataLabel',
              key: 'dataLabel',
              width: 300,
            },
            // {
            //   title: '数据键值',
            //   dataIndex: 'dataValue',
            //   key: 'dataValue',
            //   width: 300,
            // },
            {
              title: '字典颜色',
              dataIndex: 'colorType',
              key: 'colorType',
              width: 300,
            },
            {
              title: '表名',
              dataIndex: 'tableName',
              key: 'tableName',
              width: 150,
            },
          ]"
          :data-source="tableColumns"
          :pagination="{ pageSize: 10 }"
          :row-key="(record: SelectedColumn) => `${record.tableId}-${record.type}`"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'checked'">
              <Checkbox
                :checked="record.checked"
                @change="(e) => (record.checked = e.target.checked)"
              />
            </template>
            <template v-else-if="column.key === 'dictName'">
              {{ record.name }}
            </template>
            <template v-else-if="column.key === 'dictType'">
              {{ record.type }}
            </template>
            <template v-else-if="column.key === 'dataLabel'">
              <Input
                v-model:value="record.data[0].label"
                placeholder="请输入数据键值"
              />
            </template>
            <template v-else-if="column.key === 'colorType'">
              <Select
                :style="{ color: record.data[0].colorType }"
                v-model:value="record.data[0].colorType"
                :options="colorOptions"
                placeholder="请输入数据颜色"
              />
              <a-tag :color="record.data[0].colorType">
                {{ record.data[0].colorType }}
              </a-tag>
            </template>
          </template>
        </Table>
      </Card>

      <!-- 操作说明 -->
      <Card size="small" title="操作说明">
        <div class="space-y-1 text-sm text-gray-600">
          <p>1. 系统会自动筛选出 Java 类型为 Integer 和 Long 的字段</p>
          <p>2. 选择需要添加字典的字段，并为每个字段选择对应的字典类型</p>
          <p>3. 如果字典类型不存在，系统会自动创建</p>
          <p>4. 字典数据会使用字段的注释作为标签，示例值作为字典值</p>
        </div>
      </Card>
    </div>
  </Modal>
</template>
